<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 *  惊喜商品管理
 *
 *  Author:  YSX
    Date:    2022-6-1
 */
class SurprisedGoods extends Backend
{

    /**
     * SurprisedGoods模型对象
     * @var \app\admin\model\SurprisedGoods
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $searchFields = 'name,goods_code';
	 protected $multiFields = ['is_enable'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\SurprisedGoods;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where('is_del',1)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
				->where('is_del',1)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                // 启动事务
                Db::startTrans();
                try {
                    //先添加商品主表
                    $params['add_time'] = time();
                    $surprised_goods_id = Db::name('surprised_goods')->insertGetId($params);
					$attr = $this->request->post();
					// \var_dump($attr);die;
                    foreach ($attr['attr'] as $k => $v) {
                        $data[$k]['surprised_goods_id'] = $surprised_goods_id;
                        $data[$k]['attr_name'] = $v;
                    }
					//再添加规格属性表
                    $result = Db::name('surprised_goods_attr')->insertAll($data);
                    // 提交事务
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //先修改商品主表
                    $params['upd_time'] = time();
                    $res = Db::name('surprised_goods')->where('id',$row['id'])->update($params);
                    $attr = $this->request->post();
                    // \var_dump($attr);die;
                    foreach ($attr['attr'] as $k => $v) {
                        $data[$k]['surprised_goods_id'] = $row['id'];
                        $data[$k]['attr_name'] = $v;
                    }
					//先删除再添加
					$result = Db::name('surprised_goods_attr')->where('surprised_goods_id',$row['id'])->delete();
                    //再添加规格属性表
                    $result = Db::name('surprised_goods_attr')->insertAll($data);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
		//查找规格属性表信息
		$attr = Db::name('surprised_goods_attr')->where('surprised_goods_id',$row['id'])->select();
		$this->view->assign("attr", $attr);
        return $this->view->fetch();
    }

   
    /**
     * 删除商品
     */
    public function delete()
    {
		$id = input('ids');
		$res = Db::name('surprised_goods')->where('id',$id)->update(['is_del'=>2]);
		if ($res !== false) {
		    $this->success();
		} else {
		    $this->error(__('删除失败'));
		}
    }
     /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }
}
